package club.qweqwe.servlet;

import club.qweqwe.exception.BaseException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public interface ServletHelper {
    default void dispatcher(HttpServletRequest request, HttpServletResponse response, String... methodSub) throws IOException, ServletException {
        StringBuilder methodVal = new StringBuilder(request.getParameter("method"));
        try {
            Class clazz = this.getClass();
            for (int i = 0; i < methodSub.length; i++) {
                methodVal.append(methodSub[i]);
            }
            Method method = clazz.getDeclaredMethod(methodVal.toString(), HttpServletRequest.class, HttpServletResponse.class);
            method.setAccessible(false);
            method.invoke(this, request, response);
        }catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            if(e instanceof InvocationTargetException) {
                Throwable throwable = ((InvocationTargetException) e).getTargetException();
                if (throwable instanceof BaseException) {
                    String errorJson = ((BaseException) throwable).toJsonString();
                    response.setContentType("application/json");
                    response.getWriter().print(errorJson);
                }
            }
            else{
                String path = request.getServletContext().getInitParameter("ErrorPath");
                request.getRequestDispatcher(path).forward(request, response);
            }
        }
    }
}
